//
//  OAuthViewController.swift
//  微博个人swift
//
//  Created by 李灏 on 16/2/5.
//  Copyright © 2016年 lh. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    let webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBar()

        loadOauthPage()
        
    }
    //页面将要消失的时候dismiss
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    //MARK:自动填充
    @objc private func autoFill() {
        let jsString = "document.getElementById('userId').value = '18201692330', document.getElementById('passwd').value = '688100tt' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    //MARK:关闭页面
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //App Secret:b9d134e6cc6ce5708ed777b6b60dd79b
    //MARK:加载授权页面
    private func loadOauthPage() {
        //获取URL
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        //获取request
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
    }
}
//专门处理WebView的代理方法
extension OAuthViewController:UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        //开启指示器
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    //想办法获取code码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlString = request.URL?.absoluteString else {
            //url为空
            return false
        }
        //如果url不为空判断urlString中是否包含code码
        if urlString.containsString("code") {
            //截取code字符串
            //query 获取url的参数的字段和对应值
            guard let query = request.URL?.query else {
                return false
            }
            
            let codeStr = "code="
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            //用code码换取token(令牌)
//            loadAccessToken(code)
            AccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                if isSuccess{
                    SVProgressHUD.showSuccessWithStatus("登录成功")
                    //执行dismiss
                    self.dismissViewControllerAnimated(true, completion: nil)
                    //发出通知
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVC, object: "welcome")
                    
                }else {
                    SVProgressHUD.showErrorWithStatus("网络君正在睡觉,请稍后再试")
                }
                
            })
            return false
        }
        
        return true
    }
//    //加载用户的token
//    private func loadAccessToken(code:String) {
//        //url
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        //参数用字典的形式传
//        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
//        let AFN = AFHTTPSessionManager()
//        //使afn可以解析这种数据类型
//        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            //将结果转换为字典类型
//            guard let dict = result as? [String:AnyObject] else {
//                return
//            }
//            //程序到这肯定就转换为字典类型了
//            let userAccount = UserAccount(dict: dict)
////            let access_token = dict["access_token"] as! String
////            let uid = dict["uid"] as! String
////            print(access_token,uid)
//            print(userAccount)
//            self.loadUserInfo(userAccount)
//            }) { (_, error) -> Void in
//                print(error)
//        }
//    }
//    //MARK:请求用户信息
//    private func loadUserInfo(userAccount:UserAccount) {
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        //强制解包 程序包保证有值
//        let parameters = ["access_token":userAccount.access_token!,"uid":userAccount.uid!]
//        let AFN = AFHTTPSessionManager()
//        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            //将结果转换为字典
//            guard let dict = result as? [String:AnyObject] else {
//                return
//            }
//            let name = dict["name"] as! String
//            let avatar_large = dict["avatar_large"] as! String
//            userAccount.name = name
//            userAccount.avatar_large = avatar_large
//            print(userAccount)
//            userAccount.saveAccount()
//            }) { (_, error) -> Void in
//              print(error)
//        }
//    }
}
